package edu.buaa.energy;

import com.google.common.collect.AbstractIterator;
import edu.buaa.energy.transaction.ImportTemporalDataTx.MultiEntityEnergyStatus;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class EnergyStatusCsvReader extends AbstractIterator<MultiEntityEnergyStatus> implements Closeable {
    private final BufferedReader reader;
    private final Map<Integer, Integer> idColMap = new HashMap<>();
    public final File file;

    public EnergyStatusCsvReader(File file) throws IOException {
        this.file = file;
        reader = new BufferedReader(new FileReader(file));
        String header = reader.readLine();
        parseHeader(header);
    }

    @Override
    protected MultiEntityEnergyStatus computeNext() {
        try {
            String line = reader.readLine();
            if (line == null) {
                return endOfData();
            } else {
                return parseLine(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("fail to read traffic file.");
        }
    }

    private void parseHeader(String header) {
        String[] arr = header.split(",");
        for(int i=1; i<arr.length; i++){
            idColMap.put(i, Integer.parseInt(arr[i]));
        }
    }

    private MultiEntityEnergyStatus parseLine(String line) {
        HashMap<Integer, Float> r = new HashMap<>();
        String[] arr = line.split(",");
        for(int i=1; i<arr.length; i++){
            Integer id = idColMap.get(i);
            r.put(id, Float.parseFloat(arr[i]));
        }
        MultiEntityEnergyStatus e = new MultiEntityEnergyStatus();
        e.setStatus(r);
        e.setTimePoint(parseTime(arr[0]));
        return e;
    }

    private final DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/M/d H:mm");//  2012/1/1 7:00 in solar_cosmo_p, solar_cosmo_u
    private final DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//  2012-01-01 07:00:00 in others
    private int parseTime(String s) {
        LocalDateTime parsedDate;
        try {
            parsedDate = LocalDateTime.parse(s, format1);
        } catch (DateTimeParseException ignore) {
            parsedDate = LocalDateTime.parse(s, format2);
        }
        long timestamp = parsedDate.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        return Math.toIntExact(timestamp / 1000);
    }

    public void close() throws IOException {
        reader.close();
    }

}
